import { useState, useEffect } from "react";
import {
  Space,
  Table,
  Pagination,
  Input,
  Button,
  Modal,
  message,
  Form,
} from "antd";
import { SearchOutlined } from "@ant-design/icons";
import {
  Getregistrationlist,
  Cancellationofregistration,
  Searchregisteredorder,
  Getregistrationslipdetails,
} from "../../../request/zwyApi";
import "../../../assets/zwyAssets/zwyiconfont/iconfont.css";
import { format } from "date-fns"; // 导入date-fns的format函数
import modulesCss from "../../../styles/RegistrationManagement.module.css";

function RegistrationManagement() {
  const { Column } = Table;
  const [data, setData] = useState([]); // 表格数据
  const [loading, setLoading] = useState(false); // 加载状态
  const [currentPage, setCurrentPage] = useState(1); // 当前页码
  const [pageSize, setPageSize] = useState(9); // 每页数据量
  const [total, setTotal] = useState(0); // 总数据量
  const [selectIds, setIds] = useState([]); // 选中的表格行id
  const [isModalOpen, setIsModalOpen] = useState(false); // 控制删除模态框显示的状态
  const [currentId, setCurrentId] = useState(null); // 当前要删除的id
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false); // 控制详情模态框显示的状态
  const [currentDetail, setCurrentDetail] = useState(null); // 当前条目的详情

  const [bedNumber, setBedNumber] = useState(""); // 存储订单编号输入框的值
  const [phone, setPhone] = useState(""); // 存储手机号输入框的值

  useEffect(() => {
    fetchData();
  }, [currentPage, pageSize]);

  const fetchData = async (bedNumber = "", page) => {
    setLoading(true);
    try {
      const res = await Getregistrationlist({
        page: page !== undefined ? page : currentPage, // 使用提供的 page 或者 currentState.page
        size: pageSize,
        bednumber: bedNumber,
      });
      setData(res.data);
      setTotal(res.total);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

  const onChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
    setIds([]); // 切换页码时清空选中状态
  };

  const rowSelection = {
    type: "checkbox",
    selectedRowKeys: selectIds,
    onChange: (selectedRowKeys) => {
      setIds(selectedRowKeys);
    },
  };

  const handleInputChangeBedNumber = (e) => {
    setBedNumber(e.target.value);
  };

  const handleInputChangePhone = (e) => {
    setPhone(e.target.value);
  };

  const handleSearch = () => {
    Searchregisteredorder({
      page: 1,
      size: pageSize,
      id: bedNumber,
      phone: phone,
    })
      .then((res) => {
        // 将返回的数据渲染出来
        setData(res.data);
        setTotal(res.total);
        setCurrentPage(1); // 更新 currentPage 状态为 1
      })
      .catch((error) => {
        console.error("Error searching data:", error);
        message.error("搜索失败");
      });
  };

  const handleDelete = (id) => {
    setCurrentId(id); // 设置当前要删除的id
    setIsModalOpen(true); // 打开模态框
  };

  const handleBatchDelete = () => {
    if (selectIds.length > 0) {
      setCurrentId(selectIds.join(",")); // 设置当前要删除的id为选中的id数组
      setIsModalOpen(true); // 打开模态框
    }
  };

  const handleOk = async () => {
    const idsArray = currentId ? [currentId] : selectIds;
    const idsString = JSON.stringify(idsArray);
    console.log("Deleting IDs:", idsString);
    await Cancellationofregistration({ ids: idsString });
    message.success("删除成功");
    fetchData(); // 重新获取数据
    setIsModalOpen(false); // 关闭模态框
    setIds([]); // 清空选中状态
  };

  const handleCancel = () => {
    setIsModalOpen(false); // 关闭模态框
  };

  const handleViewDetail = async (record) => {
    try {
      const res = await Getregistrationslipdetails({ id: record.id });
      if (res.code === 1) {
        const formattedRegTime = format(
          new Date(res.data[0].regtime),
          "yyyy-MM-dd HH:mm:ss"
        ); // 使用date-fns格式化日期
        const detailWithFormattedTime = {
          ...res.data[0],
          regtime: formattedRegTime,
        }; // 创建一个新对象，包含格式化后的日期
        setCurrentDetail(detailWithFormattedTime);
        setIsDetailModalOpen(true);
      } else {
        message.error("获取详情失败");
      }
    } catch (error) {
      console.error("Error fetching detail data:", error);
      message.error("获取详情失败");
    }
  };

  return (
    <div style={{ padding: "10px" }} className={modulesCss.box}>
      <Space className={modulesCss.spacebox}>
        <span className={modulesCss.red} style={{ fontWeight: "600" }}>
          订单编号
        </span>
        <Input
          placeholder="请输入查询订单编号"
          style={{ width: "250px" }}
          onChange={handleInputChangeBedNumber}
          allowClear
        />
        <span style={{ marginLeft: "20px", fontWeight: "600" }}>手机号</span>
        <Input
          placeholder="请输入查询手机号"
          style={{ width: "250px" }}
          onChange={handleInputChangePhone}
          allowClear
        />
        <Button
          type="primary"
          icon={<SearchOutlined />}
          onClick={handleSearch}
          style={{ marginLeft: "20px" }}
        >
          查询
        </Button>
        <Button
          color="default"
          variant="outlined"
          onClick={handleBatchDelete}
          className={modulesCss.delbut}
        >
          删除选中
        </Button>
      </Space>

      <Table
        className={modulesCss.customborderedtable}
        rowKey={(record) => record.id}
        rowSelection={rowSelection}
        loading={loading}
        dataSource={data}
        pagination={false}
        style={{ overflow: "auto", marginBottom: "20px" }}
      >
        <Column title="订单编号" dataIndex="id" key="bednumber" />
        <Column title="患者姓名" dataIndex="name" key="department" />
        <Column title="挂号科室" dataIndex="department" key="nurse" />
        <Column title="是否为复诊" dataIndex="further" key="oxygen" />
        <Column
          title="是否自我申报48小时核酸"
          dataIndex="48report"
          key="heart"
        />

        <Column
          title="订单操作"
          key="action"
          render={(_, record) => (
            <Space size="middle">
              <a
                className="iconfont icon-empty"
                onClick={() => handleDelete(record.id)}
              ></a>{" "}
              {/* 删除按钮 */}
              <a
                className="iconfont icon-wj-wj-1"
                onClick={() => handleViewDetail(record)}
              ></a>{" "}
              {/* 查看详情按钮 */}
            </Space>
          )}
        />
      </Table>

      <Pagination
        total={total}
        current={currentPage}
        pageSize={pageSize}
        onChange={onChange}
        showSizeChanger
        showQuickJumper
        position={["bottomLeft"]}
        showTotal={(total) => `共 ${total} 条`}
      />

      {/* 自定义模态框 */}
      <Modal
        title="确认删除"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>您确定要删除这条记录吗？</p>
      </Modal>

      {/* 挂号详情对话框 */}
      <Modal
        title="挂号详情"
        open={isDetailModalOpen}
        onOk={() => setIsDetailModalOpen(false)}
        onCancel={() => setIsDetailModalOpen(false)}
        footer={
          // 添加 footer 属性
          <Space style={{ display: "flex", justifyContent: "center" }}>
            <Button onClick={() => setIsDetailModalOpen(false)}>取消</Button>
            <Button type="primary" onClick={() => setIsDetailModalOpen(false)}>
              确认
            </Button>
          </Space>
        }
      >
        {currentDetail && (
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 14 }}
            layout="horizontal"
            style={{ maxWidth: 600 }}
          >
            <Form.Item label="订单编号">
              <Input
                disabled
                value={currentDetail.id}
                style={{ marginLeft: "10px" }}
              />
            </Form.Item>
            <Form.Item label="挂号时间">
              <Input
                disabled
                value={currentDetail.regtime}
                style={{ marginLeft: "10px" }}
              />
            </Form.Item>
            <Form.Item label="患者姓名">
              <Input
                disabled
                value={currentDetail.name}
                style={{ marginLeft: "10px" }}
              />
            </Form.Item>
            <Form.Item label="是否为复诊">
              <Input
                disabled
                value={currentDetail.further}
                style={{ marginLeft: "10px" }}
              />
            </Form.Item>
            <Form.Item label="48H核酸报告">
              <Input
                disabled
                value={currentDetail["48report"]}
                style={{ marginLeft: "10px" }}
              />
            </Form.Item>
            <Form.Item label="挂号科室">
              <Input
                disabled
                value={currentDetail.department}
                style={{ marginLeft: "10px" }}
              />
            </Form.Item>

            <Form.Item label="手机号">
              <Input
                disabled
                value={currentDetail.phone}
                style={{ marginLeft: "10px" }}
              />
            </Form.Item>
          </Form>
        )}
      </Modal>
    </div>
  );
}

export default RegistrationManagement;
